#include<stdio.h>
#include<stdlib.h>
#include<fcntl.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<string.h>

typedef struct{
	char id[20];
	char pwd[20];
}User;

void register1()
{
	User user,old_user;
	char passwd[20] = {};

	//验证用户名是否已经存在
	while(1){
		int flag = 0;
		printf("please input your account number:\n");
		fgets(user.id,20,stdin);
		while(strlen(user.id)==19&&user.id[18]!='\n'){
			while(getchar()!='\n');
			printf("id long error,again!\n");
			fgets(user.id,20,stdin);
		}


		int fd = open("a.txt",O_RDWR|O_CREAT|O_APPEND,0666);
		if(fd==-1){
			perror("open");
			return ;
		}	

		while(read(fd,&old_user,sizeof(old_user))>0){
			if(strcmp(old_user.id,user.id)==0){
				flag=1;
				printf("account has exise!!\n");
				close(fd);
				break;
			}
		}
		if(!flag){
			close(fd);
			break;
		}
	
	}
	
	

	while(1){
		printf("please input your password:\n");
		fgets(user.pwd,20,stdin);
		while(strlen(user.pwd)==19&&user.pwd[18]!='\n'){
			while(getchar()!='\n');
			printf("password long error,again!\n");
			fgets(user.pwd,20,stdin);
		}
	
		printf("please input your password again:\n");
		fgets(passwd,20,stdin);
		while(strlen(user.pwd)==19&&user.pwd[18]!='\n'){
			while(getchar()!='\n');
			printf("password long error,again!\n");
			fgets(passwd,20,stdin);
		}


		if(strcmp(user.pwd,passwd)==0)
			break;
		else{
			printf("input password is not same,Again!\n");
		}
	}
	//user.pwd[strlen(user.pwd)-1]='\0';
	
	int fd = open("a.txt",O_RDWR|O_CREAT|O_APPEND,0666);
	if(fd==-1){
		perror("open");
		return -1;
	}
	

	write(fd,&user,sizeof(user));
	
	
	close(fd);
}

void sign()
{
	User user,old_user;
	

	int fd = open("a.txt",O_RDWR);
	if(fd==-1){
		perror("open");
		return -1;
	}


	printf("please input your account number:\n");
	fgets(user.id,20,stdin);
	while(strlen(user.id)==19&&user.id[18]!='\n'){
		while(getchar()!='\n');
		printf("id long error,again!\n");
	}
	
	printf("please input your password:\n");
	fgets(user.pwd,20,stdin);
	while(strlen(user.pwd)==19&&user.pwd[18]!='\n'){
		while(getchar()!='\n');
		printf("password long error,again!\n");
	}

	

	while(read(fd,&old_user,sizeof(old_user))>0){
		if(strcmp(old_user.id,user.id)==0&&strcmp(old_user.pwd,user.pwd)==0){
			printf("sign in success!\n");
			close(fd);
			//.......
			return ;
		}
	}
	printf("account number or password error!again!\n");
	
	close(fd);
}

void menu()
{
	int choice = 0;
	while(1){
		printf("1.register\n");
		printf("2.sign in\n");
		printf("3.quit\n");
		
		while(scanf("%d",&choice)!=1){
			while(getchar()!='\n');
			printf("input error!Again\n");
		}
		while(getchar()!='\n');
		system("clear");
		switch(choice){
			case 1:
				register1();
				break;
			case 2:
				sign();
				break;
			case 3:
				return;
			default:
				printf("input error!Again\n");
		}
	}	
}

int main()
{
	menu();
	return 0;
}
